const app = require('./app')
const config = require('./config')

const PORT = config.server.port || 3000
const HOST = config.server.host || '0.0.0.0'

async function startServer () {
  try {
    console.log('🚀 正在启动小说平台服务器...')

    // 启动服务器
    const server = app.listen(PORT, HOST, () => {
      console.log('\n🎉 小说平台服务器启动成功！')
      console.log(`📍 本地地址: http://localhost:${PORT}`)
      console.log(`📍 网络地址: http://192.168.1.103:${PORT}`)
      console.log(`🔍 健康检查: http://localhost:${PORT}/health`)
      console.log(`🌍 运行环境: ${config.server.env}`)
      console.log('\n✨ 小说平台，让阅读更精彩！\n')
    })

    // 优雅关闭
    const gracefulShutdown = signal => {
      console.log(`\n📴 收到 ${signal} 信号，正在优雅关闭服务器...`)
      server.close(() => {
        console.log('✅ 服务器已关闭')
        process.exit(0)
      })
    }

    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'))
    process.on('SIGINT', () => gracefulShutdown('SIGINT'))
  } catch (error) {
    console.error('❌ 服务器启动失败:', error)
    process.exit(1)
  }
}

startServer()
